require.config({
    paths: {
        'fastim': '../addons/fastim/js/fastim'
    },
    shim: {
        'fastim': {
            deps: ['css!../addons/fastim/css/fastim_default.css'],
            exports: 'FastIm'
        }
    }
});

define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'fastim'], function ($, undefined, Backend, Table, Form, FastIm) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'fastim/session/index' + location.search,
                    add_url: 'fastim/session/add',
                    edit_url: 'fastim/session/edit',
                    del_url: 'fastim/session/del',
                    multi_url: 'fastim/session/multi',
                    import_url: 'fastim/session/import',
                    record_url: 'fastim/session/record',
                    table: 'fastim_session',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {
                            field: 'type',
                            title: __('Type'),
                            searchList: {"single": __('Type single'), "service": __('Type service')},
                            formatter: Table.api.formatter.normal
                        },
                        {field: 'user.nickname', title: __('User_one'), operate: false},
                        {field: 'usertwo.nickname', title: __('User_two'), operate: false},
                        {field: 'user_one', title: __('User_one') + 'ID', visible: false, placeholder: 'IM用户ID'},
                        {field: 'user_two', title: __('User_two') + 'ID', visible: false, placeholder: 'IM用户ID'},
                        // {field: 'chat_id', title: __('service'), visible: false, searchList: {1: __('Service 1'), 2: __('Service 2'), 3: __('Service 3')}},
                        {field: 'chat_id', title: __('service'), visible: false, searchList: {1: __('Service 1'), 2: __('Service 2')}},
                        {
                            field: 'createtime',
                            title: __('Createtime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate,
                            buttons: [
                                {
                                    name: 'record',
                                    title: '沟通记录',
                                    classname: 'btn btn-xs btn-info btn-dialog',
                                    icon: 'fa fa-file-text-o',
                                    url: $.fn.bootstrapTable.defaults.extend.record_url,
                                }
                            ]
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        record: function () {
            $('.chat-records,.service-message').hide();

            FastIm.config = {__CDN__: Config.pageData.__CDN__}
            FastIm.userinfo = {
                id: Config.sessionInfo.user.id
            }

            Controller.api.renderRecord(Config.message, Config.sessionInfo, Config.pageData)

            $(document).on('scroll', function (event) {
                var e = $(event.target);

                if (!Config.pageData.nextpage) {
                    return false;
                }

                if (e.find('.chat-records') || e.find('.service-message')) {
                    var scrollTop = e.scrollTop(), elHeight = e[0].body.clientHeight, contentH = e[0].body.scrollHeight
                    if (scrollTop == (contentH - elHeight)) {
                        Fast.api.ajax({
                            url: 'fastim/session/record/ids/' + Config.sessionInfo.id + '/page/' + (parseInt(Config.pageData.page) + 1)
                        }, function (data) {
                            Controller.api.renderRecord(data.message, data.sessionInfo, data.pageData)
                            Config.pageData = data.pageData;
                            return false;
                        })
                    }
                }
            });

            // 图片预览
            $(document).on('dblclick', '.record-img', function (event) {
                var e = $(event.currentTarget),
                    src = e.attr('src');

                layer.photos({
                    photos: {
                        "title": "聊天图片预览",
                        "id": "record",
                        data: [
                            {
                                "src": src
                            }
                        ]
                    },
                    end: function () {

                    }, anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
                });
            });
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            renderRecord: function (message, sessionInfo, pageData) {
                if (sessionInfo.windowType == 'message') {

                    var messageTemplate = FastIm.template.message()
                    var recordsEL = $('.chat-records')

                    if (parseInt(pageData.page) == 1) {
                        $('.chat-records').show()
                        $('.chat-records').empty()
                    }

                    if (message.length) {
                        for (var i = 0; i < message.length; i++) {
                            recordsEL.append('<li class="chat-record-item system"><span>' + message[i].datetime + '</span></li>');
                            for (var y = 0; y < message[i].data.length; y++) {
                                var pushUser = {} // 消息上需要的用户数据
                                if (message[i].data[y].type == 'system') {
                                    var newHTML = '<li class="chat-record-item system"><span>' + message[i].data[y].message.message + '</span></li>';
                                } else {
                                    message[i].data[y].message = FastIm.build.message(message[i].data[y])
                                    if (sessionInfo.type == "single") {
                                        // 单聊消息
                                        if (message[i].data[y].sender == 'me') {
                                            pushUser.id = sessionInfo.user.id
                                            pushUser.avatar = FastIm.common.imgUrl(sessionInfo.user.avatar)
                                            pushUser.nickname = sessionInfo.user.nickname

                                            message[i].data[y].status = FastIm.common.messageStatus(message[i].data[y].status, message[i].data[y].id)
                                        } else {
                                            pushUser.id = sessionInfo.sessionUser.id
                                            pushUser.avatar = FastIm.common.imgUrl(sessionInfo.sessionUser.avatar)
                                            pushUser.nickname = sessionInfo.sessionUser.nickname

                                            message[i].data[y].status = FastIm.common.messageStatus(3, message[i].data[y].id)
                                        }
                                        pushUser.hidden_nickname = ''
                                        message[i].data[y].record_content_before = ''
                                    }

                                    var newHTML = messageTemplate({
                                        messageData: message[i].data[y],
                                        sessionInfo: {
                                            pushUser: pushUser
                                        }
                                    });
                                }
                                recordsEL.append(newHTML)
                            }
                        }
                    } else if (parseInt(pageData.page) <= 1) {
                        recordsEL.append('<div class="fastim-data-none">暂时没有聊天记录~</div>');
                    }
                } else if (sessionInfo.windowType == 'new_friends_message' || sessionInfo.windowType == 'group_notice') {
                    var serviceMessageEl = $('.service-message')
                    if (parseInt(pageData.page) <= 1) {
                        $('.fastim-window-right').show()
                        serviceMessageEl.show()
                        serviceMessageEl.html('');
                    }

                    FastIm.serviceMessageData = pageData.nextpage ? pageData : false
                    var serviceMessageTemplate = FastIm.template.serviceMessage();

                    if (message.length) {
                        for (var i = 0; i < message.length; i++) {
                            serviceMessageEl.append('<div class="service-message-datatime">' + message[i].datetime + '</div>');

                            for (var y = 0; y < message[i].data.length; y++) {
                                if (sessionInfo.windowType == 'group_notice') {
                                    // 群通知
                                    var newHTML = serviceMessageTemplate(FastIm.build.serviceMessageInfo({
                                        messageData: message[i].data[y]
                                    }, 'group_notice', {
                                        userInfo: message[i].data[y].userInfo,
                                        groupChatInfo: message[i].data[y].groupChatInfo
                                    }));
                                } else {
                                    var newHTML = serviceMessageTemplate(FastIm.build.serviceMessageInfo({
                                        messageData: message[i].data[y]
                                    }, 'new_friends_message', {
                                        userInfo: message[i].data[y].userInfo
                                    }));
                                }
                                serviceMessageEl.append(newHTML);
                            }
                        }

                        if (!pageData.nextpage) {
                            serviceMessageEl.append('<div class="fastim-data-none">没有更多消息了~</div>');
                        }
                    } else {
                        var tis = (parseInt(pageData.page) > 1) ? '没有更多消息了~' : '暂时没有消息~'
                        if ($('.service-message .fastim-data-none').length) {
                            $('.service-message .fastim-data-none').html(tis)
                        } else {
                            serviceMessageEl.append('<div class="fastim-data-none">' + tis + '</div>');
                        }
                    }
                } else if (sessionInfo.windowType == 'csr_message') {
                    var messageTemplate = FastIm.template.message()
                    var recordsEL = $('.chat-records')

                    if (parseInt(pageData.page) == 1) {
                        $('.chat-records').show()
                        $('.chat-records').empty()
                    }

                    if (message.length) {
                        for (var i = 0; i < message.length; i++) {
                            recordsEL.append('<li class="chat-record-item system"><span>' + message[i].datetime + '</span></li>');
                            for (var y = 0; y < message[i].data.length; y++) {
                                var pushUser = {} // 消息上需要的用户数据
                                if (message[i].data[y].type == 'system') {
                                    var newHTML = '<li class="chat-record-item system"><span>' + message[i].data[y].message.message + '</span></li>';
                                } else {
                                    message[i].data[y].message = FastIm.build.message(message[i].data[y])
                                    if (message[i].data[y].sender == 'me') {
                                        pushUser.id = sessionInfo.user.id
                                        pushUser.hidden_nickname = 'fastim-hidden'
                                        pushUser.avatar = FastIm.common.imgUrl(sessionInfo.user.avatar)

                                        message[i].data[y].record_content_before = 'record_content_before'
                                        message[i].data[y].status = FastIm.common.messageStatus(message[i].data[y].status, message[i].data[y].id)
                                    } else {
                                        if (message[i].data[y].csr) {
                                            pushUser = message[i].data[y].csr
                                            pushUser.avatar = FastIm.common.imgUrl(message[i].data[y].csr.avatar)
                                        } else {
                                            pushUser.type = 'service'
                                            pushUser.id = sessionInfo.sessionUser.id
                                            pushUser.avatar = FastIm.common.imgUrl(sessionInfo.sessionUser.avatar)
                                            pushUser.nickname = sessionInfo.sessionUser.nickname
                                        }

                                        message[i].data[y].status = FastIm.common.messageStatus(3, message[i].data[y].id)
                                    }
                                    var newHTML = messageTemplate({
                                        messageData: message[i].data[y],
                                        sessionInfo: {
                                            pushUser: pushUser
                                        }
                                    });

                                }
                                recordsEL.append(newHTML)
                            }
                        }
                    } else if (parseInt(pageData.page) <= 1) {
                        recordsEL.append('<div class="fastim-data-none">暂时没有聊天记录~</div>');
                    }
                }
            }
        }
    };
    return Controller;
});